import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { Spin, Tooltip, message, Menu, Dropdown, Typography } from 'antd';
import { FormOutlined, BellOutlined, CloseOutlined, DownOutlined } from '#/utils/antdIcons';
import { TRDefault } from '@/components/index.js';
import { SERVER_URL_OBJ, serverUrl } from '../../../../../../config/urlConfig';
import { TodoModal, NoticeModal, SequenceModal, SetRemindersModal } from '../index';
import {
  DETAIL_TYPES,
  TABS_LIST,
  TODO_STATUS_TYPES,
  CHECKTIME,
  REMINDER_TYPE_LIST,
  TYPE_LIST,
  IMG_TYPE,
  TRADE_TYPE_MODE,
} from '../../dictionary';
import type {
  ITodoDetailType,
  INoticeDetailType,
  ISequenceDetailType,
  ISearchFormData,
  ITodoListType,
  INoticeSequenceListType,
} from '../../type';
import { getFileUrl } from '../../tool';
import styles from './index.less';

interface IProps {
  /**
   * 搜索所有数据
   */
  searchFormData: ISearchFormData;
  /**
   * 刷新key值
   */
  setFlashKey: (e: string) => void;
  /**
   * 刷新key值
   */
  setMonthflashKey: (e: string) => void;
  /**
   * 刷新基础数据
   */
  getSearchFormData: () => void;
  /**
   * 组件是否显示
   */
  visible: boolean;
  /**
   * 控制详情是否展示
   */
  handelVisible: (e: boolean) => void;
  /**
   * 详情数据
   */
  dataSource: ITodoDetailType[] | INoticeDetailType[] | ISequenceDetailType[];
  /**
   * 当前显示的详情key
   */
  detailKey: DETAIL_TYPES;
  /**
   * 是否正在查询数据
   */
  loading: boolean;
  /**
   * 当前选中tab的key
   */
  activeKey: TABS_LIST;
  /**
   * 是否系统异常
   */
  isError: boolean;
  /**
   * 刷新数据
   */
  showDetail?: (
    record: ITodoListType & INoticeSequenceListType,
    type: DETAIL_TYPES,
  ) => Promise<void>;
  /**
   * 每一行数据
   */
  recordData?: any;
  /**
   * 按钮权限
   */
  buttonPermissions?: any;
}

const { Text } = Typography;

const Detail = (props: IProps) => {
  const {
    visible,
    detailKey,
    activeKey,
    dataSource = [],
    buttonPermissions = [],
    recordData,
    loading,
    marketId,
    isError,
    handelVisible,
    searchFormData,
    setFlashKey,
    setMonthflashKey,
    showDetail,
    getSearchFormData,
  } = props;
  const [nowData, setNowData] = useState<any>({});
  // const [selectedValue, setSelectedValue] = useState<string | number>();

  useEffect(() => {
    setNowData(dataSource ? dataSource[0] : {});
    // setSelectedValue(dataSource ? dataSource[0]?.id : '');
  }, [dataSource]);

  const downFile = (fileUrl: any, fileName = '未命名') => {
    if (!fileUrl) return;
    const _a = document.createElement('a');
    _a.href = fileUrl;
    _a.download = fileName;
    document.body.appendChild(_a);
    const evt = document.createEvent('MouseEvents');
    evt.initEvent('click', false, false);
    _a.dispatchEvent(evt);
    document.body.removeChild(_a);
  };

  const handleChange = (e: any) => {
    const keyWord = e.key;
    const data = dataSource?.find((item: any) => {
      return String(item.id) === keyWord;
    });
    // setSelectedValue(keyWord);
    if (data) {
      setNowData(data);
    } else {
      message.error('数据出错了');
      handelVisible(false);
    }
  };

  const onEdit = async () => {
    if (detailKey === DETAIL_TYPES.TODO) {
      const hasSave =
        buttonPermissions?.filter((item: any) => item.menuCode === 'pendingEditButtonV2')?.length >
        0;
      if (!hasSave) {
        return message.info('请联系管理员获取相关权限');
      }
      const result: any = await TodoModal.show({
        searchFormData: searchFormData,
        isEdit: true,
        value: nowData,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
        getSearchFormData,
        buttonPermissions,
        marketId,
      });
      if (result.index === 1) {
        showDetail && showDetail(recordData, DETAIL_TYPES.TODO);
      }
    } else if (detailKey === DETAIL_TYPES.NOTICE) {
      const hasSave =
        buttonPermissions?.filter((item: any) => item.menuCode === 'noticeAttachEditButtonV2')
          ?.length > 0;
      if (!hasSave) {
        return message.info('请联系管理员获取相关权限');
      }
      const result: any = await NoticeModal.show({
        searchFormData: searchFormData,
        isEdit: true,
        value: nowData,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
      });
      if (result.index === 1) {
        showDetail && showDetail(recordData, DETAIL_TYPES.NOTICE);
      }
    } else if (detailKey === DETAIL_TYPES.SEQUENCE) {
      const hasSave =
        buttonPermissions?.filter((item: any) => item.menuCode === 'noticeAttachEditButtonV2')
          ?.length > 0;
      if (!hasSave) {
        return message.info('请联系管理员获取相关权限');
      }
      const result: any = await SequenceModal.show({
        searchFormData: searchFormData,
        isEdit: true,
        value: nowData,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
      });
      if (result.index === 1) {
        showDetail && showDetail(recordData, DETAIL_TYPES.SEQUENCE);
      }
    }
  };

  // 提醒设置弹框
  const handleSetReminders = async () => {
    const hasSave =
      buttonPermissions?.filter((item: any) => item.menuCode === 'reminderButtonV2')?.length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const result: any = await SetRemindersModal.show({
      searchFormData,
      value: {
        ...nowData,
        id: nowData?.id ? [nowData?.id] : null,
      },
      isEdit: true,
      getSearchFormData,
      marketId,
    });
    if (result.index === 1) {
      showDetail && showDetail(recordData, DETAIL_TYPES.TODO);
    }
  };

  // 预览
  const handelPreview = async (obj: any, system: boolean) => {
    const urlPrefix = 'https://view.officeapps.live.com/op/view.aspx';
    if (system) {
      //系统
      let _purl = await getFileUrl(obj);
      if (
        obj?.annexName?.includes('.doc') ||
        obj?.annexName?.includes('.xls') ||
        obj?.annexName?.includes('.lsx')
      ) {
        _purl = `${serverUrl}/annex/annex/downLoadFile/${obj.annexPath}`;
        _purl = `${urlPrefix}?src=${encodeURIComponent(_purl)}`;
      }
      window.open(_purl);
    } else {
      const url = `${serverUrl}/annex/annex/downLoadFile/${obj?.annexId || ''}?mandatory=false`;
      if (
        obj.annexName.includes('.pdf') ||
        obj.annexName.includes('.png') ||
        obj.annexName.includes('.jpg')
      ) {
        window.open(url);
      } else {
        window.open(`${urlPrefix}?src=${serverUrl}/annex/annex/downLoadFile/${obj?.annexId || ''}`);
      }
    }
  };

  // 下载
  const handleDownload = async (obj: any, system: boolean) => {
    if (system) {
      // 下载
      /*  const client = new OSS({
          region: 'oss-cn-beijing',
          accessKeyId: 'LTAI4G7w6tvFNPQ4q2hcHcD6',
          accessKeySecret: 'ZgALLEnmeqjjcTxlJnDEKKfJ6R5GUy',
          bucket: 'tianrun',
        });
        const url = client.signatureUrl(obj.annexPath, {
          expires: 3600,
          response: {
            'content-disposition': 'attachment; filename="' + obj.annexName + '"',
          },
        });
        window.open(url); */
      const { CLIENT_ENV } = process.env;
      const url = CLIENT_ENV === 'release' ? '' : SERVER_URL_OBJ.test;
      const _durl = `${url}/annex/annex/downLoadFile/${obj.annexPath}`;
      downFile(_durl, obj.annexName);
    } else {
      window.open(`${serverUrl}/annex/annex/downLoadFile/${obj.annexId}`);
    }
  };

  const toDealWithFile = (strOne: string, strTwo: string, strThree?: string) => {
    const arrOne = strOne?.split(',') || [];
    const arrTwo = strTwo?.split(',') || [];
    const arrThree = strThree ? strThree?.split(',') : [];
    const result = arrOne?.map((item, i) => {
      return {
        annexId: item,
        annexPath: arrThree[i],
        annexName: arrTwo[i],
        logoType: arrTwo[i]?.substring(arrTwo[i]?.length - 3) || '',
      };
    });
    return result;
  };

  const menu = (_dataSource: any) => (
    <Menu onClick={handleChange}>
      {_dataSource.map((item: any) => {
        return (
          <Menu.Item key={item.id}>
            <Tooltip placement={'topLeft'} title={item?.transactionArrange || item?.title || ''}>
              {item?.transactionArrange || item?.title || ''}
            </Tooltip>
          </Menu.Item>
        );
      })}
    </Menu>
  );

  const LabelValue = (data: { label: string; value: React.ReactNode }) => {
    return (
      <div className={styles.labelValue}>
        <div className={styles.label}>{data.label}</div>
        <div className={styles.value}>{data.value}</div>
      </div>
    );
  };

  const TitleContent = ({ useData }: any) => {
    return (
      <div className={styles.titleContent}>
        <div className={styles.left}>
          {detailKey === DETAIL_TYPES.TODO ? useData?.transactionArrange : useData?.title}
        </div>
        {useData?.type !== TYPE_LIST.SYSTEM_NOTICE && useData?.type !== TYPE_LIST.SYSTEM_SEQUENCE && (
          <div className={styles.right} onClick={onEdit}>
            <FormOutlined className={styles.logo} />
            <span className={styles.edit}>编辑</span>
          </div>
        )}
      </div>
    );
  };

  const attachments = (
    type: TYPE_LIST,
    attachmentIds: string,
    attachmentNames: string,
    attachmentPaths: string,
  ) => {
    const data = toDealWithFile(attachmentIds, attachmentNames, attachmentPaths);
    const isSystem: boolean =
      type === TYPE_LIST.SYSTEM_NOTICE || type === TYPE_LIST.SYSTEM_SEQUENCE;
    return (
      <div className={styles.attachmentNames}>
        {data.map((item) => {
          return (
            <Tooltip
              placement={'topLeft'}
              title={
                <div className={styles.upload}>
                  <div className={styles.lable}>{item?.annexName || ''}</div>
                  <div className={styles.options}>
                    <a
                      className={styles.preView}
                      style={{ marginRight: '10px' }}
                      onClick={() => handelPreview(item, isSystem)}
                    >
                      预览
                    </a>
                    <a className={styles.load} onClick={() => handleDownload(item, isSystem)}>
                      下载
                    </a>
                  </div>
                </div>
              }
            >
              <div className={styles.iconBox} style={data.length > 3 ? { width: '100px' } : {}}>
                <span>
                  <img src={IMG_TYPE[item.logoType]} />
                </span>
                <span className={styles.fileName} style={data.length > 3 ? { width: '80px' } : {}}>
                  {item?.annexName || ''}
                </span>
              </div>
            </Tooltip>
          );
        })}
      </div>
    );
  };

  const Header = () => {
    const showTitle =
      activeKey === TABS_LIST.TODO_TABS_TYPE && detailKey === DETAIL_TYPES.TODO
        ? '待办详情'
        : activeKey === TABS_LIST.NOTICE_TABS_TYPE && detailKey === DETAIL_TYPES.NOTICE
        ? '公告详情'
        : activeKey === TABS_LIST.SEQUENCE_TABS_TYPE && detailKey === DETAIL_TYPES.SEQUENCE
        ? '交易序列详情'
        : '';
    const showSubTitle =
      activeKey === TABS_LIST.TODO_TABS_TYPE && detailKey === DETAIL_TYPES.NOTICE
        ? `关联公告${dataSource?.length > 1 ? dataSource?.length : 1}`
        : activeKey === TABS_LIST.TODO_TABS_TYPE && detailKey === DETAIL_TYPES.SEQUENCE
        ? `关联序列${dataSource?.length > 1 ? dataSource?.length : 1}`
        : (activeKey === TABS_LIST.SEQUENCE_TABS_TYPE ||
            activeKey === TABS_LIST.NOTICE_TABS_TYPE) &&
          detailKey === DETAIL_TYPES.TODO
        ? `关联待办${dataSource?.length > 1 ? dataSource?.length : 1}`
        : '';
    return (
      <div className={styles.headerContainer}>
        {showTitle ? (
          <div className={styles.showTitle}>{showTitle}</div>
        ) : dataSource?.length > 1 ? (
          <div className={styles.option}>
            <Dropdown
              overlay={menu(dataSource)}
              placement="bottomCenter"
              overlayClassName={styles.dropdownA}
            >
              <div className={styles.showTitle}>
                <span className={styles.content}>{showSubTitle}</span>
                <DownOutlined />
              </div>
            </Dropdown>
          </div>
        ) : (
          <Tooltip
            placement={'topLeft'}
            title={nowData?.transactionArrange || nowData?.title || ''}
          >
            <div className={styles.showTitle}>
              <span>{showSubTitle}</span>
            </div>
          </Tooltip>
        )}
        <div onClick={() => handelVisible && handelVisible(false)}>
          <CloseOutlined className={styles.inVisible} />
        </div>
      </div>
    );
  };

  // 待办详情
  const TodoDetail = ({ useData }: { useData: ITodoDetailType }) => {
    const calendarTime =
      useData?.pendingStartTime && useData?.pendingEndTime
        ? `${moment(useData?.pendingStartTime).format('HHmm')}-${moment(
            useData?.pendingEndTime,
          ).format('HHmm')}`
        : '-';
    const data = TODO_STATUS_TYPES.find((item) => item.value === useData?.status);
    const reminderTypeData = REMINDER_TYPE_LIST.find(
      (item) => item.value === useData?.reminderType,
    );
    const list: { label: string; value: React.ReactNode }[] = [
      {
        label: '待办日期',
        value: useData?.calendarDate ? moment(useData?.calendarDate).format('YYYYMMDD') : '-',
      },
      { label: '待办时间', value: calendarTime },
      {
        label: '相关单元',
        value: (
          <Tooltip
            placement={'topLeft'}
            overlayClassName={styles.overlayClassName}
            title={
              <div>
                {useData?.stationList?.length > 0
                  ? useData?.stationList.map((item) => item.label)?.join(',')
                  : '-'}
              </div>
            }
          >
            {useData?.stationList?.length > 0
              ? useData?.stationList.map((item) => item.label)?.join(',')
              : '-'}
          </Tooltip>
        ),
      },
    ];

    const warnText =
      useData?.remindFlag === '1' &&
      ((useData?.reminderTime && useData?.reminderTime.length > 0) ||
        reminderTypeData ||
        useData?.reminderList)
        ? `提醒设置：${
            useData?.reminderTime && useData?.reminderTime.length > 0
              ? useData?.reminderTime
                  .map((item) => {
                    return CHECKTIME[String(item)]?.label;
                  })
                  .join(',')
              : '无'
          } / ${reminderTypeData ? reminderTypeData.label : '无'} / 提醒对象(${
            useData?.reminderList ? useData?.reminderList?.length : 0
          }人)：${
            useData?.reminderList && useData?.reminderList?.length > 0
              ? useData?.reminderList.map((item) => item.name).join(',')
              : '无'
          }`
        : '提醒设置';

    const Title = () => {
      return (
        <div
          className={warnText !== '提醒设置' ? styles.warn : styles.otherWarn}
          onClick={handleSetReminders}
        >
          <BellOutlined className={styles.logo} />
          <Tooltip
            placement={'topLeft'}
            overlayClassName={styles.overlayClassName}
            title={<div>{warnText}</div>}
          >
            {warnText}
          </Tooltip>
        </div>
      );
    };
    return (
      <div className={styles.main}>
        <div className={styles.header}>
          <Header />
        </div>
        <div className={styles.content}>
          <TitleContent useData={useData} />
          <div className={styles.subInfo}>
            <div
              className={styles.status}
              style={{ color: 'var(--font)', backgroundColor: data?.backgroundColor }}
            >
              {data?.label}
            </div>
            <div className={styles.createUserName}>{useData?.createName}</div>
            <div className={styles.createTime}>
              <span className={styles.name}>创建于</span>
              <span>{useData?.createTime}</span>
            </div>
          </div>
          {list.map((item) => {
            return <LabelValue {...item} key={item.label} />;
          })}

          {/*<Tooltip placement={'topLeft'} title={<Title />}>*/}
          {/*  <Title />*/}
          {/*</Tooltip>*/}
        </div>
      </div>
    );
  };

  // 公告详情
  const NoticeDetail = ({ useData }: { useData: INoticeDetailType }) => {
    const list: { label: string; value: React.ReactNode }[] = [
      { label: '发布单位', value: useData?.marketName ? useData?.marketName : '-' },
      {
        label: '正文',
        value: useData?.content ? (
          <Tooltip
            placement={'topLeft'}
            overlayInnerStyle={{ minWidth: '600px' }}
            overlayClassName={styles.overlayClassName}
            title={<div dangerouslySetInnerHTML={{ __html: useData.content }} />}
          >
            <Text style={{ width: 600 }} ellipsis>
              {/* <div
                className={styles['htmlContent']}
                dangerouslySetInnerHTML={{ __html: useData.content }}
              /> */}
              {useData?.content}
            </Text>
          </Tooltip>
        ) : (
          '-'
        ),
      },
      { label: '公告作者', value: useData?.author ? useData?.author : '-' },
      {
        label: '发布时间',
        value: useData?.publishTime ? moment(useData?.publishTime).format('YYYYMMDD') : '-',
      },
      {
        label: '附件',
        value: useData?.attachmentIds
          ? attachments(
              useData?.type,
              useData?.attachmentIds,
              useData?.attachmentNames,
              useData?.attachmentPaths,
            )
          : '-',
      },
      {
        label: '相关单元',
        value: (
          <Tooltip
            placement={'topLeft'}
            overlayClassName={styles.overlayClassName}
            title={<div>{useData?.stationNames ? useData?.stationNames : '-'}</div>}
          >
            {useData?.stationNames ? useData?.stationNames : '-'}
          </Tooltip>
        ),
      },
    ];
    return (
      <div className={styles.main}>
        <div className={styles.header}>
          <Header />
        </div>
        <div className={styles.content}>
          <TitleContent useData={useData} />
          <div className={styles.subInfo}>
            <div className={styles.createUserName}>{useData?.createUserName}</div>
            <div className={styles.createTime}>
              <span className={styles.name}>创建于</span>
              <span>
                {useData?.createTime
                  ? moment(useData?.createTime).format('YYYY-MM-DD HH:mm:ss')
                  : ''}
              </span>
            </div>
          </div>
          {list.map((item) => {
            return <LabelValue {...item} />;
          })}
        </div>
      </div>
    );
  };

  // 交易序列详情
  const SequenceDetail = ({ useData }: { useData: ISequenceDetailType }) => {
    const declarationTime =
      useData?.declarationStartTime && useData?.declarationEndTime
        ? `${moment(useData?.declarationStartTime).format('HHmm')}-${moment(
            useData?.declarationEndTime,
          ).format('HHmm')}`
        : '-';
    const executionDate =
      useData?.executionStartDate && useData?.executionEndDate
        ? `${moment(useData?.executionStartDate).format('YYYYMMDD')}-${moment(
            useData?.executionEndDate,
          ).format('YYYYMMDD')}`
        : '-';
    const list: { label: string; value: React.ReactNode }[] = [
      { label: '发布单位', value: useData?.marketName ? useData?.marketName : '-' },
      {
        label: '交易方式',
        value: useData?.tradeTypeMode ? TRADE_TYPE_MODE[useData.tradeTypeMode] : '-',
      },
      { label: '交易申报时间', value: declarationTime },
      { label: '交易执行时间', value: executionDate },
      {
        label: '附件',
        value: useData?.attachmentIds
          ? attachments(
              useData?.type,
              useData?.attachmentIds,
              useData?.attachmentNames,
              useData?.attachmentPaths,
            )
          : '-',
      },
      {
        label: '相关单元',
        value: (
          <Tooltip
            placement={'topLeft'}
            overlayClassName={styles.overlayClassName}
            title={<div>{useData?.stationNames ? useData?.stationNames : '-'}</div>}
          >
            {useData?.stationNames ? useData?.stationNames : '-'}
          </Tooltip>
        ),
      },
    ];
    return (
      <div className={styles.main}>
        <div className={styles.header}>
          <Header />
        </div>
        <div className={styles.content}>
          <TitleContent useData={useData} />
          <div className={styles.subInfo}>
            <div className={styles.createUserName}>{useData?.createUserName}</div>
            <div className={styles.createTime}>
              <span className={styles.name}>创建于</span>
              <span>
                {useData?.createTime
                  ? moment(useData?.createTime).format('YYYY-MM-DD HH:mm:ss')
                  : ''}
              </span>
            </div>
          </div>
          {list.map((item) => {
            return <LabelValue {...item} />;
          })}
        </div>
      </div>
    );
  };

  return visible ? (
    <div className={`${!visible ? styles.outContainer : styles.containerBox} ${styles.container}`}>
      <Spin spinning={loading}>
        {isError ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : dataSource?.length === 0 ? (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        ) : (
          <div className={styles.content}>
            {detailKey === DETAIL_TYPES.TODO && <TodoDetail useData={nowData} />}
            {detailKey === DETAIL_TYPES.NOTICE && <NoticeDetail useData={nowData} />}
            {detailKey === DETAIL_TYPES.SEQUENCE && <SequenceDetail useData={nowData} />}
          </div>
        )}
      </Spin>
    </div>
  ) : null;
};

export default Detail;
